package com.base.essearch.component;

import cn.hutool.core.lang.Console;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import com.base.essearch.webupload.entity.FileRecord;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author zhangguoqing
 * @date 2021/2/21 15:00
 * @Description: 分割批量插入数据
 * 从源代码中可以看到pgsql语句的参数数量,即行数*列数之积必须小于等于32767.
 *
 * 如果一次插入的数据量太多，使得参数数量超过了最大值，只能分批插入了。
 */
@Component
public class PartitionArrayUtil<T>  {

    public  Map<Integer, List<T>> partition(List<T> list) {

        if (list.isEmpty()) {
            return null;
        }
        T t = list.get(0);
        Field[] fields = t.getClass().getDeclaredFields();
        int capacity = 30;
        Map<Integer, List<T>> result = MapUtil.newHashMap();

        int size = list.size();
        int count = ((Double) Math.ceil(Double.valueOf(size * 10) / capacity)).intValue();

        capacity=size/count;
        for (int i = 0; i <= count; i++) {
            int end = capacity * (i + 1);
            if (end > size){
                end = size;
            }
            result.put(i, list.subList(capacity * i, end));
        }
        return result;
    }

    public static void main(String[] args) {
        List<FileRecord> list=new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            FileRecord re=new FileRecord();
            re.setId(i+"");
            list.add(re);
        }
        Map<Integer, List<FileRecord>> partition = new PartitionArrayUtil<FileRecord>().partition(list);
        System.out.println(partition);
    }

}
